﻿using StackExchange.Redis;
using System;
using System.Drawing;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace EasyRedis
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }


        private ConnectionMultiplexer redis;
        private IDatabase db;
        private void button1_Click(object sender, EventArgs e)
        {
            // 连接到Redis服务器
            try
            {
                string basicUrl=textBox_url.Text;   
                string pass=textBox_pass.Text;
                if (!string.IsNullOrEmpty(pass))
                {
                    basicUrl += ",password=" + pass;
                }
                redis = ConnectionMultiplexer.Connect(basicUrl); // 替换为你的Redis服务器地址
                db = redis.GetDatabase(); // 默认使用db0

                comboBoxDB.Items.Clear();
                for (int i = 0; i < 16; i++)
                {
                    comboBoxDB.Items.Add("db" + i);
                }
                comboBoxDB.SelectedIndex = 0; // 默认选择第一个数据库

                MessageBox.Show("连接成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法连接到Redis服务器: " + ex.Message);
            }
        }
        private void LoadKeysToListBox()
        {
            if (db == null)
                return;

            listBoxKeys.Items.Clear();

            var server = redis.GetServer(redis.GetEndPoints()[0]);
            foreach (var key in server.Keys())
            {
                listBoxKeys.Items.Add(key.ToString());
            }
            textBox_value.Text = "";
        }
        public void CloseConnect()
        {
            try
            {
                // Check if redis connection is valid
                if (redis != null && redis.IsConnected)
                {
                    // Close connection
                    redis.Close();
                    redis = null;
                }
            }
            catch(Exception ex)
            {

            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            CloseConnect();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseConnect();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            comboBoxOperations.Items.Add("GET");
            comboBoxOperations.Items.Add("SET");
            comboBoxOperations.Items.Add("DEL");
            comboBoxOperations.Items.Add("GET-ALL-KEY");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string operation = comboBoxOperations.SelectedItem.ToString();
            string key = textBoxKey.Text;

            switch (operation)
            {
                case "GET":
                    // 调用获取值的方法
                    GetValueForKey(key);
                    break;
                case "SET":
                    // 要求进一步的输入或对话框，以便获取值用于SET
                    SetValueForKey(key);
                    LoadKeysToListBox();
                    break;
                case "DEL":
                    // 调用删除键的方法
                    DeleteKey(key);
                    LoadKeysToListBox();
                    break;
                case "GET-ALL-KEY":
                    // 调用删除键的方法
                    GetAllKey();
                    break;
                default:
                    MessageBox.Show("未知操作.");
                    break;
            }
        }

        private void GetAllKey()
        {
            LoadKeysToListBox();
        }

        private void GetValueForKey(string key)
        {
            if (db != null)
            {
                RedisValue value = db.StringGet(key);
                if (!value.IsNull)
                {
                    MessageBox.Show($"键 '{key}' 的值为: '{value}'.");
                }
                else
                {
                    MessageBox.Show($"键 '{key}' 不存在。");
                }
            }
        }

        private void SetValueForKey(string key)
        {
            // 这里应有进一步逻辑获取需要设置的值
            string valueToSet = textBox_value.Text;
            if (db != null)
            {
                db.StringSet(key, valueToSet);
                MessageBox.Show($"键 '{key}' 已设置值 '{valueToSet}'.");
            }
        }

        private void DeleteKey(string key)
        {
            if (db != null)
            {
                bool success = db.KeyDelete(key);
                if (success)
                {
                    MessageBox.Show($"键 '{key}' 已被删除。");
                }
                else
                {
                    MessageBox.Show($"删除键 '{key}' 失败，键可能不存在。");
                }
            }
        }

        private void timer_status_check_Tick(object sender, EventArgs e)
        {
            this.Invoke((Action)(() => {
                status_label.Text = CheckConnectionStatus(out bool success);
                status_label.ForeColor = success?Color.Green:Color.Red;
            }));
        }

        // 模拟检查连接状态的方法
        private string CheckConnectionStatus(out bool success)
        {
            success = false;
            // 使用Redis Ping命令检测连接状态
            if (redis != null && redis.IsConnected)
            {
                try
                {
                    // PING命令是检测连接是否存活的一个很好的选择
                    var latency = db.Ping();
                    success = true;
                    return $"已连接 - 延迟: {latency.TotalMilliseconds}ms";
                }
                catch
                {
                    return "连接失败";
                }
            }
            else
            {
                return "未连接";
            }
        }

        private void listBoxKeys_SelectedIndexChanged(object sender, EventArgs e)
        {
            //将选中的key的值写到textbox里
            if (listBoxKeys.SelectedItem == null)
                return;

            var key = listBoxKeys.SelectedItem.ToString();

            // 从 Redis 获取对应键的值
            var value = db.StringGet(key);

            // 将获取到的值显示在 TextBox 控件中
            textBox_value.Text = value;
        }

        private void comboBoxDB_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (redis != null && redis.IsConnected)
            {
                int dbIndex = comboBoxDB.SelectedIndex;
                db = redis.GetDatabase(dbIndex);
                // 你可以在这里更新 UI 或添加其他逻辑来处理数据库切换
                MessageBox.Show($"已切换到 {comboBoxDB.SelectedItem.ToString()}");
            }
        }
    }
}
